// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env:'cloud1-6grwwt4c9c6f3350'
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db= cloud.database()
  const studentCollection = db.collection('pc_student')
  let openid = wxContext.OPENID
  let {sn,name,nickName,avatarUrl} = event

  console.log(sn,name,nickName,avatarUrl)

  let res = await studentCollection.where({
    sn,name
  }).get()
  console.log(res)

  let user={}
  let reg='ok'
  let rrMsg = ''

  if(res.data.length==0){
    reg = 'err'
    errMsg = '没找到匹配的学号姓名'
  }else{
    if(res.data[0].avatarUrl){
      reg = 'err'
      errMsg = '学号：'+sn+'已经被微信昵称'+res.data[0].nickName+'绑定'
    }else{
      user = {...res.data[0],nickName,avatarUrl}
      res = await studentCollection.doc(res.data[0]._id).update({
        data:{
          nickName,avatarUrl,openid
        }
      })
    }
  }

  return {
    reg,errMsg,user
  }
}